use diesel::SqliteConnection;
use diesel::Connection;

use chrono::NaiveDateTime;
use chrono::NaiveDate;
use chrono::NaiveTime;
use diesel::debug_query;
use diesel::insert_into;
use diesel::prelude::*;

use diesel::sqlite::Sqlite;
use serde::Deserialize;
use std::error::Error;

mod schema {
    diesel::table! {
        users {
            id -> Integer,
            name -> Text,
            hair_color -> Nullable<Text>,
            created_at -> Timestamp,
            updated_at -> Timestamp,
        }
    }
}

pub use schema::users ;

#[derive(Queryable, PartialEq, Debug,Insertable)]
pub struct User {
    id: i32,
    name: String,
    hair_color: Option<String>,
    created_at: NaiveDateTime,
    updated_at: NaiveDateTime,
}

use crate::users::dsl;

fn main()  {
    let url = "sqlite://test.db".to_string();
    let mut connection=SqliteConnection::establish(&url).expect("sqlite数据库连接失败");

    let new_user = User { id: 333, name: "你懂的 ".to_string(), hair_color: Some("red".to_string()), created_at: NaiveDate::from_ymd_opt(2016, 7, 8).unwrap().and_hms_opt(9, 10, 11).unwrap(), updated_at:NaiveDate::from_ymd_opt(2016, 7, 8).unwrap().and_hms_opt(9, 10, 11).unwrap()};

    diesel::insert_into(users::table)
        .values(&new_user)
        .execute(&mut connection)
        .expect("Error saving new post");

    let results = dsl::users.order(users::id.desc())
    .load::<User>(&mut connection).expect("查询失败");
 
    for item in results {
        println!("{:?}", item.id);
        println!("----------\n");
        println!("{}", item.name);
    }
}